package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.OrderInfoMapper;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.util.SeckillCodeMsg;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Override
    @Transactional
    public String doSeckill(Long userId, Long seckillId) {
        //减库存
        int count = seckillGoodService.decrCount(seckillId);
        if (count == 0) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCKCOUNT_OVER);
        }

        //保存订单详情
        String orderNo = createOrder(userId, seckillId);
        //保存秒杀数据
        seckillOrderService.createSeckillOrder(userId, orderNo, seckillId);
        return orderNo;
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        return orderInfoMapper.get(orderNo);
    }

    @Override
    public int changStatus(String orderNo, Integer status) {
        return orderInfoMapper.changStatus(orderNo, status);
    }

    @Override
    public void changPayStatus(String out_trade_no, Integer status) {
        orderInfoMapper.changPayStatus(out_trade_no, status);
    }

    private String createOrder(Long userId, Long seckillId) {
        OrderInfo orderInfo = new OrderInfo();
        SeckillGoodVO seckillGoodVO = seckillGoodService.getSeckillGoodById(seckillId);
        BeanUtils.copyProperties(seckillGoodVO, orderInfo);
        orderInfo.setCreateDate(new Date());
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");
        orderInfo.setUserId(userId);
        orderInfoMapper.save(orderInfo);

        return orderInfo.getOrderNo();
    }
}
